package com.technodo;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.technodo.play.ClassicPlayActivity;
import com.technodo.play.GuideActivity;
import com.technodo.play.MultiPlayerActivity;
import com.technodo.play.UnderTheHoodActivity;
import com.technodo.utils.GlobalPreferences;
import com.technodo.utils.StringConstants;

public class TechnodoMain extends Activity {

	private String TAG = getClass().getName();
	 

	private static GlobalPreferences globalPreferences = GlobalPreferences.getGlobalPreferences();
	/**
	 * Called when activity launched for the first time.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Setup DataDir
		SharedPreferences prefs = getSharedPreferences("TechnodoPrefs", 0);
		globalPreferences.settechnodoPrefs(prefs);		
		globalPreferences.setDataDir("/data/data/" + this.getPackageName() + "/");

		// Make Window Fullscreen as it is a game
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_technodo_main);
	
		// method to play sound
		GlobalPreferences.playSound(getApplicationContext(),R.raw.technodo_start);
		
		//To setup Listners
		setUpItems();

	}
	
	

	private void setUpItems() {
		Button classicPlayButton = (Button) findViewById(R.id.classicPlay);
		classicPlayButton.setOnClickListener(onClickMenu);

		Button multiPlayerButton = (Button)findViewById(R.id.multiPlayer);
		multiPlayerButton.setOnClickListener(onClickMenu);

		Button howToPlayButton = (Button)findViewById(R.id.howtoPlay);
		howToPlayButton.setOnClickListener(onClickMenu);

		Button underTheHoodButton = (Button)findViewById(R.id.underTheHood);
		underTheHoodButton.setOnClickListener(onClickMenu);

		Button exitButton = (Button)findViewById(R.id.exit);
		exitButton.setOnClickListener(onClickMenu);
		
	}

	protected void onButtonClick (View v) {
		switch (v.getId()) {

		case R.id.classicPlay:

			Log.d(TAG, "In classic play activity");

			Intent classicPlayIntent = new Intent(this , ClassicPlayActivity.class);
			startActivity(classicPlayIntent);
			break;

		case R.id.multiPlayer:
			Log.d(TAG, "In multiPlayer activity");
			Intent multiPlayerIntent = new Intent(this , MultiPlayerActivity.class);
			startActivity(multiPlayerIntent);
			break;

		case R.id.howtoPlay:
			Log.d(TAG, "In guide activity");
			Intent howToPlayIntent = new Intent(this , GuideActivity.class);
			startActivity(howToPlayIntent);
			break;

		case R.id.underTheHood:
			Log.d(TAG, "In underTheHood activity");
			Intent underTheHoodIntent = new Intent(this , UnderTheHoodActivity.class);
			startActivityForResult(underTheHoodIntent, 23897);
			break;	

		case R.id.exit:
			finish();
			break;
		default:
			break;
		}
	}

	private View.OnClickListener onClickMenu = new View.OnClickListener() {
		public void onClick(View view) {
			GlobalPreferences.stopSound();
			onButtonClick(view);
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_technodo_main, menu);
		return true;
	}


	@Override
	public void onResume() {
		super.onResume();
		try {

			Bundle extras = getIntent().getExtras();
			if(extras != null) {
				// Could have a master reset intent to reset game data from settings
				// This will clear all game data from the system and allow the user to have a fresh start
				boolean masterreset = extras.getBoolean(StringConstants.KEY_LAUNCHER_RESET);
				if(masterreset == true) {

					Log.i(TAG, "Master Reset: Clearing all data");
					deleteGameDirectory();

					Log.i(TAG, "First run copying assets to data folder....");
					copyAssetsToData();
					Log.i(TAG, "Copied Assets to data folder");
					globalPreferences.setSoundon(true);
					globalPreferences.incrementGamesPlayed();
					finish();
				}
			} 

			// FIXME: check presence of External Storage
			// Or flag error to user - game needs external storage (around
			// 15-20MB)

			// Check if first run
			// Copy assets to the data directory
			// FIXME: Uncomment following line, it is only for testing purposes that we copy json each time
			if(globalPreferences.getGamesPlayed() == 0) {
				Log.i(TAG, "Master Reset: Clearing all data");
				deleteGameDirectory();

				Log.i(TAG, "First run copying assets to data folder....");
				copyAssetsToData();
				Log.i(TAG, "Copied Assets to data folder");
				globalPreferences.setSoundon(true);
				globalPreferences.incrementGamesPlayed();
			}

		} catch (NullPointerException n) {
			Log.e(TAG, "Null Pointer Exception: " + n.getMessage());
		} catch (FileNotFoundException e) {
			Log.e(TAG, "FileNotFoundException : " + e.getMessage());
			e.printStackTrace();
		} catch (IOException io) {
			Log.e(TAG, "IOException : " + io.getMessage());
			io.printStackTrace();
		} finally {
		}

	}

	/**
	 * Delete the game directory
	 */
	private void deleteGameDirectory() {

		File rootDataDir = new File(globalPreferences.getDataDir());
		if(rootDataDir.exists() == true) {
			DeleteRecursive(rootDataDir);
		}
	}

	/**
	 * Delete a directory recursively
	 * @param dir Directory to be deleted
	 */
	void DeleteRecursive(File dir)
	{
		Log.d(TAG, "DELETEPREVIOUS TOP" + dir.getPath());
		if (dir.isDirectory())
		{
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) 
			{
				File temp =  new File(dir, children[i]);
				if(temp.isDirectory())
				{
					Log.d(TAG, "Recursive Call" + temp.getPath());
					DeleteRecursive(temp);
				}
				else
				{
					Log.d(TAG, "Delete File" + temp.getPath());
					boolean b = temp.delete();
					if(b == false)
					{
						Log.d(TAG, "DELETE FAIL");
					}
				}
			}

			dir.delete();
		}
	}

	/**
	 *  Copy all game related assets to Data partition
	 * @throws IOException when file or directory is not found
	 */
	private void copyAssetsToData() throws IOException {
		String dataDir = "data";

		// Clear all preferences
		globalPreferences.clearAllPreferences();
		copyFileOrDir(dataDir);

		return;

	}


	/**
	 *  Copies all file from any area to data partition
	 * @param path Directory or File Path to copy
	 */
	private void copyFileOrDir(String path) {

		AssetManager assetManager = this.getAssets();
		String assets[] = null;
		try {
			assets = assetManager.list(path);
			if (assets.length == 0) {
				copyFile(path);
			} else {
				// String fullPath = "/data/data/" + this.getPackageName() + "/"
				// + path;
				String fullPath = globalPreferences.getDataDir() + path;
				File dir = new File(fullPath);
				if (!dir.exists())
					dir.mkdir();
				for (int i = 0; i < assets.length; ++i) {
					copyFileOrDir(path + "/" + assets[i]);
				}
			}
		} catch (Exception ex) {
			Log.e(TAG, "I/O Exception" + ex.getMessage());
		}
	}

	/**
	 *  Copies a single file into the data partition from assets
	 * @param filename copy file from asset to /data section
	 */
	private void copyFile(String filename) {
		AssetManager assetManager = this.getAssets();

		boolean status = globalPreferences.fileAddToPreferences(filename);
		Log.d(TAG, "File classified as " + filename + "  : " + status);

		InputStream in = null;
		OutputStream out = null;
		try {
			in = assetManager.open(filename);
			// String newFileName = "/data/data/" + this.getPackageName() + "/"
			// + filename;
			String newFileName = globalPreferences.getDataDir() + filename;
			out = new FileOutputStream(newFileName);

			byte[] buffer = new byte[1024];
			int read;
			while ((read = in.read(buffer)) != -1) {
				out.write(buffer, 0, read);
			}			
			Log.d(TAG, "Copied File : " + newFileName + " classied as (config) : " + status);
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		} finally {
			try {
				if(in != null)
					in.close();
				in = null;
				if(out != null) {
					out.flush();
					out.close();
				}
				out = null;
			} catch (IOException e) {
				Log.e(TAG, e.getMessage());
			}
		}
	}	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		GlobalPreferences.stopSound();
	}

}
